<template>
	<div class="import">
		<preview-images ref="previewImages" />
		<div class="product-name">{{ productData.name }}</div>
		<el-card class="box-card" v-if="productId != 11654">
			<div slot="header" class="clearfix">
				<span style="font-size: 16px; font-weight: bold"
					>投保企业（上传营业执照可自动识别企业信息）</span
				>
				<el-checkbox
					v-model="sameAsToubao"
					size="medium"
					style="float: right; padding: 3px 0"
					>被保企业同投保企业
				</el-checkbox>
			</div>
			<el-form
				:model="toubaoForm"
				:rules="rules"
				label-width="130px"
				ref="toubaoForm"
				v-loading="toubaoLoading"
			>
				<el-form-item label="企业名称" prop="customerName" required>
					<el-select
						v-model="toubaoForm.customerName"
						@change="(val) => getToubaoById(val)"
						size="mini"
						filterable
						allow-create
						default-first-option
						class="field"
						placeholder="请选择企业"
					>
						<el-option
							v-for="customer in customerOptions"
							:value="customer.customerId"
							:label="customer.customerName"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="联系人" prop="contactName" required>
					<el-input
						v-model="toubaoForm.contactName"
						size="mini"
						placeholder="请输入联系人"
						class="field"
					/>
				</el-form-item>
				<el-form-item label="统一社会信用代码" prop="certNum" required>
					<el-input
						v-model="toubaoForm.certNum"
						placeholder="请输入统一社会信用代码"
						size="mini"
						class="field"
					/>
				</el-form-item>
				<el-form-item label="所在区县" required>
					<el-form-item
						prop="provinceCode"
						style="display: inline-block; margin: 0"
					>
						<el-select
							v-model="toubaoForm.provinceCode"
							@change="toubaoForm.cityCode = toubaoForm.regionCode = ''"
							placeholder="省"
							style="width: 120px; margin-right: 5px"
						>
							<el-option
								v-for="province in areaOptions.provinces"
								:key="province.dictcode"
								:value="province.dictcode"
								:label="province.dictname"
								>{{ province.dictname }}</el-option
							>
						</el-select>
					</el-form-item>
					<el-form-item
						prop="cityCode"
						style="display: inline-block; margin: 0"
					>
						<el-select
							v-model="toubaoForm.cityCode"
							@change="toubaoForm.regionCode = ''"
							placeholder="市"
							style="width: 120px; margin-right: 5px"
						>
							<el-option
								v-for="city in areaOptions.citys"
								:key="city.dictcode"
								:value="city.dictcode"
								:label="city.dictname"
								>{{ city.dictname }}</el-option
							>
						</el-select>
					</el-form-item>
					<el-form-item
						prop="regionCode"
						style="display: inline-block; margin: 0"
					>
						<el-select
							v-model="toubaoForm.regionCode"
							placeholder="区"
							style="width: 120px; margin-right: 5px"
						>
							<el-option
								v-for="region in areaOptions.regions"
								:key="region.dictcode"
								:value="region.dictcode"
								:label="region.dictname"
								>{{ region.dictname }}</el-option
							>
						</el-select>
					</el-form-item>
				</el-form-item>
				<el-form-item label="手机号码" prop="contactPhone" required>
					<el-input
						v-model="toubaoForm.contactPhone"
						placeholder="请输入手机号码"
						size="mini"
						class="field"
					/>
				</el-form-item>
				<!-- <el-form-item label="所在地区" prop="area">
					<el-input v-model="toubaoForm.area" size="mini" class="field" />
				</el-form-item> -->
				<el-form-item label="详细地址" prop="address" required>
					<el-input
						v-model="toubaoForm.address"
						placeholder="请输入详细地址"
						size="mini"
						class="field"
					/>
				</el-form-item>
				<el-form-item label="营业执照" prop="businessLicense" required>
					<el-upload
						:class="{ 'hide-upload-button': toubaoForm.businessLicense }"
						:before-remove="toubaoBeforeRemove"
						:on-preview="() => onPreview(toubaoForm.businessLicense.url)"
						:limit="0"
						:http-request="handleToubaoUpload"
						:file-list="[toubaoForm.businessLicense]"
						list-type="picture-card"
					>
						<i class="el-icon-plus"></i>
					</el-upload>
				</el-form-item>
				<el-form-item label="示例">
					<el-image
						style="width: 148px; height: 148px"
						src="https://qtbx.meibaokeji.com.cn/employer/static/2022images/yyzz.png"
						:preview-src-list="[
							'https://qtbx.meibaokeji.com.cn/employer/static/2022images/yyzz.png'
						]"
					>
					</el-image>
				</el-form-item>
				<el-form-item
					v-if="toubaoForm.businessLicense && toubaoForm.contactPhone"
					label="短信验证码"
					prop="code"
				>
					<el-input
						v-model="toubaoForm.code"
						placeholder="请输入短信验证码"
						size="mini"
						class="field"
					></el-input>
				</el-form-item>
				<div style="grid-column: -1/1; text-align: center">
					<el-button
						size="small"
						type="primary"
						@click="sendCode"
						v-if="
							toubaoForm.businessLicense &&
							toubaoForm.contactPhone &&
							!this.toubaoForm.code
						"
						:loading="codeLoading"
						>发送验证码</el-button
					>
					<el-button size="small" type="primary" v-else @click="saveToubao">
						确认
					</el-button>
				</div>
			</el-form>
		</el-card>
		<el-card class="box-card" v-if="sameAsToubao === false">
			<div slot="header" class="clearfix">
				<span style="font-size: 16px; font-weight: bold"
					>被保企业（上传营业执照可自动识别企业信息）</span
				>
			</div>
			<el-form
				:model="beibaoForm"
				:rules="rules"
				label-width="130px"
				ref="beibaoForm"
				v-loading="beibaoLoading"
			>
				<el-form-item label="企业名称" prop="customerName" required>
					<el-select
						v-model="beibaoForm.customerName"
						@change="(val) => getBeibaoById(val)"
						size="mini"
						filterable
						allow-create
						default-first-option
						class="field"
						placeholder="请选择企业"
					>
						<el-option
							v-for="customer in customerOptions"
							:value="customer.customerId"
							:label="customer.customerName"
						/>
					</el-select>
				</el-form-item>
				<el-form-item
					label="行业大类"
					prop="premiumMode"
					v-if="productData.premiumMode"
				>
					<el-select
						v-model="beibaoForm.premiumMode"
						size="mini"
						filterable
						allow-create
						default-first-option
						class="field"
						placeholder="请选择行业大类"
					>
						<el-option
							v-for="mode in productData.premiumMode"
							:value="mode.value"
							:label="mode.name"
							:key="mode.value"
						/>
					</el-select>
				</el-form-item>

				<el-form-item label="联系人" prop="contactName" required>
					<el-input
						v-model="beibaoForm.contactName"
						size="mini"
						placeholder="请输入联系人"
						class="field"
					/>
				</el-form-item>
				<el-form-item label="统一社会信用代码" prop="certNum" required>
					<el-input
						v-model="beibaoForm.certNum"
						placeholder="请输入统一社会信用代码"
						size="mini"
						class="field"
					/>
				</el-form-item>

				<el-form-item label="手机号码" prop="contactPhone" required>
					<el-input
						v-model="beibaoForm.contactPhone"
						placeholder="请输入手机号码"
						size="mini"
						class="field"
					/>
				</el-form-item>
				<el-form-item label="所在区县" required>
					<el-form-item
						prop="provinceCode"
						style="display: inline-block; margin: 0"
					>
						<el-select
							v-model="beibaoForm.provinceCode"
							@change="beibaoForm.cityCode = beibaoForm.regionCode = ''"
							placeholder="省"
							style="width: 120px; margin-right: 5px"
						>
							<el-option
								v-for="province in areaOptions.provinces"
								:key="province.dictcode"
								:value="province.dictcode"
								:label="province.dictname"
								>{{ province.dictname }}</el-option
							>
						</el-select>
					</el-form-item>
					<el-form-item
						prop="cityCode"
						style="display: inline-block; margin: 0"
					>
						<el-select
							v-model="beibaoForm.cityCode"
							@change="beibaoForm.regionCode = ''"
							placeholder="市"
							style="width: 120px; margin-right: 5px"
						>
							<el-option
								v-for="city in areaOptions.citys"
								:key="city.dictcode"
								:value="city.dictcode"
								:label="city.dictname"
								>{{ city.dictname }}</el-option
							>
						</el-select>
					</el-form-item>
					<el-form-item
						prop="regionCode"
						style="display: inline-block; margin: 0"
					>
						<el-select
							v-model="beibaoForm.regionCode"
							placeholder="区"
							style="width: 120px; margin-right: 5px"
						>
							<el-option
								v-for="region in areaOptions.regions"
								:key="region.dictcode"
								:value="region.dictcode"
								:label="region.dictname"
								>{{ region.dictname }}</el-option
							>
						</el-select>
					</el-form-item>
				</el-form-item>
				<el-form-item label="详细地址" prop="address" required>
					<el-input
						v-model="beibaoForm.address"
						placeholder="请输入详细地址"
						size="mini"
						class="field"
					/>
				</el-form-item>
				<el-form-item label="营业执照" prop="businessLicense" required>
					<el-upload
						:class="{ 'hide-upload-button': beibaoForm.businessLicense }"
						:before-remove="beibaoBeforeRemove"
						:on-preview="() => onPreview(beibaoForm.businessLicense.url)"
						:limit="0"
						:http-request="handleBeibaoUpload"
						:file-list="[beibaoForm.businessLicense]"
						list-type="picture-card"
					>
						<i class="el-icon-plus"></i>
					</el-upload>
				</el-form-item>
				<el-form-item label="示例">
					<el-image
						style="width: 148px; height: 148px"
						src="https://qtbx.meibaokeji.com.cn/employer/static/2022images/yyzz.png"
						:preview-src-list="[
							'https://qtbx.meibaokeji.com.cn/employer/static/2022images/yyzz.png'
						]"
					>
					</el-image>
				</el-form-item>

				<div style="grid-column: -1/1; text-align: center">
					<el-button size="small" type="primary" @click="saveBeibao">
						确认
					</el-button>
				</div>
			</el-form>
		</el-card>
		<el-card class="box-card">
			<div slot="header" class="clearfix">
				<span style="font-size: 16px; font-weight: bold">保障期限 </span>
			</div>
			<el-form
				:model="qixianForm"
				:rules="qixianRules"
				label-width="130px"
				ref="qixianForm"
				v-loading="qixianLoading"
			>
				<el-form-item label="保单起期" prop="startTime" required>
					<el-date-picker
						v-model="qixianForm.startTime"
						size="mini"
						placeholder="请选择开始时间"
						type="date"
						value-format="yyyy-MM-dd"
						style="width: 100%"
						:picker-options="startDatePickerOptions"
					/>
					<span class="append-fix">00:00:00</span>
				</el-form-item>
				<el-form-item label="保单止期" prop="endTime" required>
					<el-date-picker
						v-model="qixianForm.endTime"
						:readonly="
							!productData.policyType ||
							!!productData.insuranceType ||
							productData.policyType === 4
						"
						size="mini"
						placeholder="请选择结束时间"
						type="date"
						value-format="yyyy-MM-dd"
						style="width: 100%"
					/>
					<span class="append-fix">23:59:59</span>
				</el-form-item>
				<el-form-item label="保单期间" prop="endTime" required>
					<el-input
						v-model="baoxianqijian"
						readonly
						size="mini"
						style="width: 100%"
					>
					</el-input>
				</el-form-item>
				<div style="grid-column: -1/1; text-align: center">
					<el-button size="small" type="primary" @click="saveQixian">
						确认
					</el-button>
				</div>
			</el-form>
		</el-card>
		<el-card class="box-card" v-if="showPerson" v-loading="personLoading">
			<div slot="header" class="clearfix">
				<span style="font-size: 16px; font-weight: bold">保障人员</span>
			</div>

			<div style="overflow: hidden; margin-bottom: 15px">
				<el-button
					size="mini"
					type="primary"
					icon="el-icon-plus"
					@click="addPerson"
					>新增</el-button
				>

				<el-button
					size="mini"
					type="primary"
					icon="el-icon-document-add"
					style="float: right"
					@click="() => $refs.import.click()"
					:loading="importLoading"
					>批量导入</el-button
				>
				<el-button
					size="mini"
					icon="el-icon-download"
					style="float: right"
					@click="downloadTemplate"
					><b>下载</b> 模板</el-button
				>
				<el-button size="mini" icon="el-icon-delete" style="float: right"
					>一键清空</el-button
				>
				<input type="file" ref="import" @change="handleImportPerson" hidden />
			</div>
			<el-table
				size="small"
				:data="personList"
				border
				v-loading="importLoading"
			>
				<el-table-column
					label="错误提示"
					prop="_error_"
					width="204"
					class-name="_error_"
					v-if="personList.find((v) => v._error_)"
				/>

				<el-table-column type="index" label="序号" />

				<el-table-column
					v-for="field in personTableFields"
					:label="field.name"
					:prop="field.fieldName"
					:key="field.fieldName"
					:width="field.width || 'auto'"
				>
					<template class="tb-h" slot="header">
						<span style="color: red" v-show="field.isNull">*</span>
						<span>{{ field.name }}</span>
					</template>
					<template slot-scope="scope">
						<el-input
							v-if="field.formType === 'text'"
							size="mini"
							v-model="scope.row[field.fieldName]"
							:placeholder="`请输入${field.name}`"
							@input="(val) => onInput(val, field, scope.row)"
						/>
						<el-select
							v-if="field.formType === 'select'"
							size="mini"
							v-model="scope.row[field.fieldName]"
							:placeholder="`请选择${field.name}`"
							@change="(val) => onSelect(val, field, scope.row)"
						>
							<el-option
								v-for="opt in field.setting"
								:value="opt.value"
								:label="opt.name"
							/>
						</el-select>
						<el-date-picker
							v-if="field.formType === 'date'"
							v-model="scope.row[field.fieldName]"
							size="mini"
							:placeholder="field.name"
							type="date"
							value-format="yyyy-MM-dd"
							:picker-options="pickerOptions"
						/>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="64">
					<template slot-scope="scope">
						<el-button
							type="text"
							size="mini"
							icon="el-icon-circle-close"
							@click="removePerson(scope.$index)"
							>移除</el-button
						>
					</template>
				</el-table-column>
			</el-table>
			<div style="grid-column: -1/1; text-align: center; margin-top: 12px">
				<el-button size="small" type="primary" @click="savePerson">
					保存
				</el-button>
			</div>
		</el-card>

		<div style="margin-block: 20px; text-align: center">
			<el-button @click="save" type="primary" size="medium">保存</el-button>
		</div>
	</div>
</template>

<script>
import {
	productDetail,
	createBusiness,
	customerList,
	customerById,
	uploadFile,
	licenseOcr,
	sendSMSCode,
	saveInsure,
	saveBeibao,
	queryTargetByType,
	querySubjectData,
	importPerson,
	downloadExcel,
	saveQixian,
	savePerson,
	save,
	getBusinessById
} from '@/api'
import _ from 'lodash'
import * as REGEXP from '@/const/REGEXP'
import { downloadByResponse } from '@/utils/download'
import { queryCitys, queryAreaByCode } from '@/api/form'
import moment from 'moment'
import { start } from 'nprogress'
import { TRUE } from 'sass'
var urlSearchParams = new URLSearchParams(location.search)
var UrlSearch = {}
for (let [key, value] of urlSearchParams.entries()) {
	UrlSearch[key] = value
}
import { transformKey } from '@/utils'
const baoform = {
	customerName: '',
	certNum: '', // 统一代码
	address: '', // 详细地址
	contactName: '', // 联系人
	contactPhone: '', // 手机号
	businessLicense: '', // 营业执照
	code: '', // 验证码
	provinceCode: '',
	cityCode: '',
	regionCode: '',

	// 产品订单的类型 1国寿类 2太保类
	policyType: 1 // 默认国寿类
}
export default {
	beforeRouteEnter(to, from, next) {
		if (to.query.productId == 11653) {
			next({ name: 'InsureInputCar', query: to.query })
			return
		}
		if (to.query.productId == 11654) {
			next({ path: '/11654/input', query: to.query })
			return
		}
		next()
	},
	data() {
		var that = this

		const startTime = moment().add(1, 'days').format('yyyy-MM-DD')
		return {
			productData: {},
			sameAsToubao: true, // 被保企业同投保企业
			businessId: '',

			toubaoForm: Object.assign({}, baoform),
			beibaoForm: Object.assign({}, baoform),
			toubaoBusinessLicenseFile: null,
			beibaoBusinessLicenseFile: null,
			toubaoLoading: false,
			beibaoLoading: false,
			rules: {
				customerName: [{ required: true, message: '请选择企业' }],
				certNum: [{ required: true, message: '请输入统一社会信用代码' }],
				address: [{ required: true, message: '请输入详细地址' }],
				provinceCode: [{ required: true, message: '请选择省份' }],
				cityCode: [{ required: true, message: '请选择地市' }],
				regionCode: [{ required: true, message: '请选择区县' }],
				contactName: [{ required: true, message: '请输入联系人' }],
				contactPhone: [{ required: true, message: '请输入联系方式' }],
				businessLicense: [{ required: true, message: '请上传营业执照' }],
				code: [{ required: true, message: '请输入短信验证码' }]
			},
			customerOptions: [],

			// 保障期限
			qixianForm: {
				startTime,
				endTime: ''
			},
			qixianRules: {
				startTime: { required: true },
				endTime: { required: true }
			},
			qixianLoading: false,

			startDatePickerOptions: {
				disabledDate(date) {
					const start = new Date(startTime)
					return date.getTime() < start.getTime() - 24 * 3600000
				}
			},

			// 人员信息
			personTableFields: [],
			personList: [],
			importLoading: false, // 导入loading
			personLoading: false, // 人员保存loading
			// 地区选择
			areaOptions: {
				provinces: [],
				citys: [],
				regions: []
			},

			pickerOptions: {
				disabledDate(time) {
					const timeStramp = time.getTime()
					const { startTime, endTime } = that.qixianForm
					const minTime = new Date(startTime).getTime()
					const maxTime = new Date(endTime).getTime()
					return minTime > timeStramp && maxTime < timeStramp
				}
			}
		}
	},
	computed: {
		productId() {
			return this.$route.query.productId * 1
		},
		baoxianqijian() {
			var { startTime, endTime } = this.qixianForm
			if (startTime && endTime) {
				var diffTime =
					new Date(endTime).getTime() - new Date(startTime).getTime()
				return Math.floor(diffTime / 1000 / 60 / 60 / 24) + 1
			} else {
				return '--'
			}
		}
	},
	async created() {
		if (this.productId == 11654) {
			this.sameAsToubao = false
			this.$set(this.beibaoForm, 'premiumMode', '')
			this.rules.premiumMode = [{ required: true, message: '请选择行业大类' }]
		}

		var { businessId, policyType } = this.$route.query
		if (businessId) {
			this.fetchBusiness(businessId)
			this.fetchTableList(businessId)
		}
		if (!businessId) {
			var servData = await createBusiness({
				productId: this.productId,
				...UrlSearch
			}).then((res) => res.data)
			businessId = servData.businessId
			policyType = servData.policyType
		}
		this.businessId = businessId
		this.policyType = policyType || 1 // 默认国寿类

		this.fetchCustomerOptions()
		this.fetchTableFields()

		productDetail(this.productId).then((res) => {
			this.productData = res.data

			// 开启录屏
			const channel = 'picc-driving'
			const oldChannel = localStorage.getItem('channel')
			if (oldChannel !== channel) {
				localStorage.setItem('channel', channel)
				Recorder.renew()
			}
			if (Recorder.status() !== 'living') {
				Recorder.start({
					channel,
					compress: true,
					testServer: 'https://service.aiins.cn/insurance/api/open/putJsonV2'
				})
			}
		})

		queryCitys().then((res) => {
			this.areaOptions.provinces = res.data
		})
	},
	mounted() {},
	watch: {
		sameAsToubao: {
			handler(same) {
				if (same) {
					this.beibaoForm = Object.assign({}, this.toubaoForm)
				}
			},
			immediate: false
		},
		'toubaoForm.provinceCode'(val) {
			queryAreaByCode({
				dictcode: val
			}).then((res) => {
				this.areaOptions.citys = res.data
			})
		},
		'toubaoForm.cityCode'(val) {
			queryAreaByCode({
				dictcode: val
			}).then((res) => {
				this.areaOptions.regions = res.data
			})
		},
		'beibaoForm.provinceCode'(val) {
			queryAreaByCode({
				dictcode: val
			}).then((res) => {
				this.areaOptions.citys = res.data
			})
		},
		'beibaoForm.cityCode'(val) {
			queryAreaByCode({
				dictcode: val
			}).then((res) => {
				this.areaOptions.regions = res.data
			})
		},
		'qixianForm.startTime': {
			handler(val) {
				if (this.productData.policyType === 4) {
					this.qixianForm.endTime = moment(this.qixianForm.startTime)
						.add(1, 'month')
						.date(1)
						.subtract(1, 'days')
						.format('yyyy-MM-DD')
				}
				if (this.productData.insuranceType) {
					var { duration, type } = this.productData.insuranceType
					this.qixianForm.endTime = moment(this.qixianForm.startTime)
						.add(duration, type)
						.subtract(1, 'days')
						.format('yyyy-MM-DD')
				}
			},
			immediate: true
		},
		productData() {
			if (this.productData.policyType === 4) {
				this.qixianForm.endTime = moment(this.qixianForm.startTime)
					.add(1, 'month')
					.date(1)
					.subtract(1, 'days')
					.format('yyyy-MM-DD')
				this.sameAsToubao = false
			}
			if (this.productData.insuranceType) {
				var { duration, type } = this.productData.insuranceType
				this.qixianForm.endTime = moment(this.qixianForm.startTime)
					.add(duration, type)
					.subtract(1, 'days')
					.format('yyyy-MM-DD')
			}
		},
		'productData.insuranceType'(val) {
			var { duration, type } = this.productData.insuranceType
			this.qixianForm.endTime = moment(this.qixianForm.startTime)
				.add(duration, type)
				.subtract(1, 'days')
				.format('yyyy-MM-DD')
		}
	},
	methods: {
		// 获取订单id
		fetchBusiness(businessId) {
			getBusinessById(businessId).then((res) => {
				if (res.data === '您已完成投保') {
					this.$router.replace({
						path: '/insure/pay-success',
						query: this.$route.query
					})
					return
				}
				this.toubaoForm = res.data.customer
				this.beibaoForm = res.data.relation
				this.qixianForm = {
					startTime: res.data.startTime,
					endTime: res.data.endTime
				}
				if (res.data.startTime && res.data.endTime) {
					this.showPerson = true
				}
			})
		},
		// 获取企业选项列表
		fetchCustomerOptions() {
			customerList().then((res) => {
				this.customerOptions = res.data
			})
		},
		// 地区变化
		// areaChangeHandle(val) {
		// 	console.log(this.$refs.areaCascader.getCheckedNodes())
		// },
		save() {
			this.loading = true
			save({
				same: this.sameAsToubao,
				businessId: this.businessId
			})
				.then((res) => {
					// const docUrl = res.data
					// 跳转下一步
					if (this.policyType === 2) {
						this.$router.push({
							name: 'Wait',
							query: {
								businessId: this.businessId,
								productId: this.productId
							}
						})
					} else {
						this.$router.push({
							name: 'Payment-No-Require',
							query: {
								businessId: this.businessId,
								productId: this.productId
							}
						})
					}
					this.$message.success('投保信息已录入')
				})
				.finally(() => {
					this.loading = false
				})
		},

		handleToubaoUpload({ file }) {
			uploadFile({ file, batchId: '' }).then((res) => {
				this.toubaoForm.businessLicense = res
				res.url = res.filePath
				// this.toubaoBusinessLicenseFile = res
				licenseOcr(res).then((res) => {
					for (let key in res.data) {
						this.toubaoForm[key] = res.data[key]
					}
				})
			})
		},
		handleBeibaoUpload({ file }) {
			uploadFile({ file, batchId: '' }).then((res) => {
				this.beibaoForm.businessLicense = res
				res.url =
					(process.env.NODE_ENV === 'development'
						? 'http://192.168.0.196:9999'
						: '') + res.filePath
				licenseOcr(res).then((res) => {
					for (let key in res.data) {
						this.beibaoForm[key] = res.data[key]
					}
				})
			})
		},
		toubaoBeforeRemove(file, filelist) {
			this.toubaoForm.businessLicense = null
		},
		beibaoBeforeRemove(file, filelist) {
			this.beibaoForm.businessLicense = null
		},
		getBeibaoById(id, type) {
			customerById(id).then((res) => {
				res.data.businessLicense.url =
					(process.env.NODE_ENV === 'development'
						? 'http://192.168.0.196:9999'
						: '') + res.data.businessLicense.filePath
				const tempForm = this.beibaoForm
				for (let key in res.data) {
					tempForm[key] = res.data[key]
				}
			})
		},
		getToubaoById(id) {
			customerById(id).then((res) => {
				res.data.businessLicense.url =
					(process.env.NODE_ENV === 'development'
						? 'http://192.168.0.196:9999'
						: '') + res.data.businessLicense.filePath
				const tempForm = this.toubaoForm
				for (let key in res.data) {
					tempForm[key] = res.data[key]
				}
			})
		},
		sendCode() {
			this.codeLoading = true
			sendSMSCode(this.toubaoForm.contactPhone)
				.then(() => {
					this.$message.success('验证码已发送')
				})
				.finally(() => {
					this.codeLoading = false
				})
		},
		saveToubao() {
			const postData = Object.assign({}, this.toubaoForm)
			postData.businessLicense = postData.businessLicense.fileId
			this.$refs.toubaoForm.validate((valid) => {
				if (valid) {
					this.toubaoLoading = true
					saveInsure(postData, {
						type: 1,
						businessId: this.businessId
					}).finally(() => {
						this.toubaoLoading = false
					})
				}
			})
		},
		saveBeibao() {
			const postData = Object.assign({}, this.beibaoForm)
			postData.businessLicense = postData.businessLicense.fileId
			this.$refs.beibaoForm.validate((valid) => {
				if (valid) {
					this.beibaoLoading = true
					saveBeibao(postData, {
						type: 2,
						businessId: this.businessId
					}).finally(() => {
						this.beibaoLoading = false
					})
				}
			})
		},
		// 保险期限
		saveQixian() {
			this.$refs.qixianForm.validate((valid) => {
				if (valid) {
					this.qixianLoading = true
					saveQixian(this.businessId, this.qixianForm)
						.then(() => {
							this.showPerson = true
						})
						.finally(() => {
							this.qixianLoading = false
						})
				}
			})
		},
		// ----- 人员列表 ------
		// 表头
		fetchTableFields() {
			queryTargetByType(this.productId).then((res) => {
				this.personTableFields = res.data
			})
		},
		// 表体
		fetchTableList(businessId) {
			querySubjectData(businessId).then((res) => {
				this.personList = res.data.list.map(transformKey)
			})
		},
		// 新增一条
		addPerson() {
			const item = {}
			for (let field of this.personTableFields) {
				item[field.fieldName] = field.value
				if (field.fieldName === 'policy_effective_date') {
					item[field.fieldName] = this.qixianForm.startTime
				}
				if (field.fieldName === 'policy_expiration_date') {
					item[field.fieldName] = this.qixianForm.endTime
				}
			}
			this.personList.unshift(item)
		},
		// 移除人员
		removePerson(index) {
			this.personList.splice(index, 1)
		},
		// 保存人员
		savePerson() {
			this.personLoading = true
			savePerson(this.businessId, this.personList)
				.then((res) => {
					res.subjects = res.subjects.map(transformKey)
					res.subjects.forEach((element, index) => {
						element._error_ = res.data?.[index] || ''
					})
					this.personList = res.subjects
				})
				.finally(() => {
					this.personLoading = false
				})
		},
		// 模板导入
		handleImportPerson(event) {
			const file = event.target.files[0]
			const id = this.businessId
			this.importLoading = true
			importPerson({ file, id, page: 1, limit: 20 })
				.then((res) => {
					res.subjects = res.subjects.map(transformKey)
					res.subjects.forEach((element, index) => {
						element._error_ = res.data?.[index] || ''
					})
					this.personList = res.subjects
				})
				.finally(() => {
					this.importLoading = false
				})
			event.target.value = ''
		},
		downloadTemplate() {
			downloadExcel({
				productId: this.productId,
				...this.qixianForm
			}).then(downloadByResponse)
		},
		// 表格输入
		onInput(val, field, row) {
			// 出生日期自动带出
			var idNum = row.id_num || row.idNum
			if (field.name == '证件号码') {
				if (REGEXP.idNum.test(val) && (row.id_type === 0 || row.idType === 0)) {
					row.birth =
						idNum.slice(6, 10) +
						'-' +
						idNum.slice(10, 12) +
						'-' +
						idNum.slice(12, 14)
					row.gender = (idNum[16] * 1) % 2
				}
			}
		},
		onSelect(val, field, row) {
			var idNum = row.id_num || row.idNum
			if (field.name == '证件类型') {
				if (REGEXP.idNum.test(row.idNum || row.id_num) && val === 0) {
					row.birth =
						idNum.slice(6, 10) +
						'-' +
						idNum.slice(10, 12) +
						'-' +
						idNum.slice(12, 14)
					row.gender = (idNum[16] * 1) % 2
				}
			}
		},
		onPreview(url) {
			this.$refs.previewImages.open(url)
		}
	},
	components: {}
}
</script>

<style lang="scss" scoped="scoped">
.box-card {
	margin-bottom: 20px;
}
.product-name {
	font-size: 20px;
	font-weight: 600;
	text-align: center;
	margin-block: 20px;
}
.import ::v-deep {
	.el-form {
		display: grid;
		gap: 15px;
		grid-template-columns: 1fr 1fr;
	}
	.el-form-item {
		margin-bottom: 0;
	}

	.el-table__header tr th {
		font-size: 13px;
		color: #333;
		background: #fbfcff;
	}
	._error_ {
		color: #f22 !important;
	}
}
.field {
	width: 100%;
}
.append-fix {
	position: absolute;
	right: 1em;
	top: 50%;
	transform: translateY(-50%);
	color: #999;
}
.hide-upload-button ::v-deep .el-upload--picture-card {
	display: none;
}
</style>
